package red.lixiang.service.impl;

import red.lixiang.dao.ProductDAO;
import red.lixiang.model.BaseInfo;
import red.lixiang.model.Product;
import red.lixiang.service.InventoryService;
import red.lixiang.utils.ProductUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

import static red.lixiang.base.ProductConfig.productColorMap;
import static red.lixiang.base.ProductConfig.productSizeMap;

@Repository
public class InventoryServiceImpl implements InventoryService {

    @Autowired
    private ProductDAO productDAO;

    @Override
    public BaseInfo getAllProduct() {

        List<Product> products = productDAO.getAllProduct();
        //开始过滤
        products.stream();

        return new BaseInfo("0","dd",productDAO.getAllProduct());
    }

    @Override
    public BaseInfo insertProduct(List<Product> products) {

        if(products.get(0).getBarCode()==null||products.get(0).getBarCode().equals("")){

            int count = 0;
            for (Product product : products) {
                product.setColorName(productColorMap.get(product.getColorCode()));
                product.setSizeName(productSizeMap.get(product.getSizeCode()));
                product.setProductName(ProductUtils.getProductNameByProductId(product.getProductId()));
                String barCode = product.getProductId()+product.getColorCode()+product.getSizeCode();
                product.setBarCode(barCode);
                Product exitProduct = productDAO.getProductByBarCode(barCode);
                if(exitProduct!=null){
                    //已有的，只需要更新就可以了
                    productDAO.updateProductNum(barCode,product.getProductNum());
                    count++;
                }else {
                    //需要额外插入的
                    productDAO.insertProduct(product);
                }
            }

            System.out.println(count);

        }

        return null;
    }

    @Override
    public BaseInfo updateProduct(Product product) {

        productDAO.updateProductByBarCode(product);

        return new BaseInfo("0","OK");
    }

    @Override
    public BaseInfo updateProductImage(String fileName) {

        String likeCode =fileName.substring(0,fileName.indexOf('.'));
        productDAO.updateProductImage(likeCode,fileName);


        return new BaseInfo("0","ok");
    }
}
